<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>备份管理</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          icon="el-icon-refresh"
          @click="getList"
        >刷新</el-button>
      </div>
      <div class="backup-toolbar">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleCreateBackup"
          v-hasPermi="['disk:storage:backupDisk']"
        >创建备份</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="backupList"
        style="width: 100%; margin-top: 15px;"
      >
        <el-table-column
          label="备份ID"
          align="center"
          prop="backupId"
          width="280"
        />
        <el-table-column
          label="备份时间"
          align="center"
          prop="backupTime"
          width="180"
        />
        <el-table-column
          label="文件数量"
          align="center"
          prop="fileCount"
        />
        <el-table-column
          label="备份大小"
          align="center"
        >
          <template slot-scope="scope">
            {{ formatFileSize(scope.row.totalSize) }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="200"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleViewBackup(scope.row)"
              v-hasPermi="['disk:storage:listBackupFiles']"
            >查看文件</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-download"
              @click="handleRestore(scope.row)"
              v-hasPermi="['disk:storage:restoreFiles']"
            >恢复文件</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 备份文件列表对话框 -->
    <el-dialog title="备份文件列表" :visible.sync="fileDialogVisible" width="800px">
      <el-table :data="backupFiles" height="400" v-loading="fileLoading">
        <el-table-column label="文件名" prop="name" />
        <el-table-column label="大小" width="120">
          <template slot-scope="scope">
            {{ formatFileSize(scope.row.size) }}
          </template>
        </el-table-column>
        <el-table-column label="类型" width="120">
          <template slot-scope="scope">
            {{ scope.row.isDir ? '文件夹' : '文件' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleRestoreFile(scope.row)"
              v-if="!scope.row.isDir"
            >恢复</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 恢复备份对话框 -->
    <el-dialog title="恢复文件" :visible.sync="restoreDialogVisible" width="500px">
      <div>
        <p>确定要恢复选中的文件吗？恢复操作会覆盖现有文件。</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="restoreDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRestore" :loading="restoreLoading">确定恢复</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBackups, listBackupFiles, restoreFiles, createBackup } from '@/api/disk/backup'

export default {
  name: 'DiskBackup',
  data() {
    return {
      // 遮罩层
      loading: true,
      fileLoading: false,
      restoreLoading: false,
      // 备份列表
      backupList: [],
      // 备份文件列表
      backupFiles: [],
      // 选中的备份
      currentBackup: null,
      // 选中的文件
      selectedFiles: [],
      // 对话框
      fileDialogVisible: false,
      restoreDialogVisible: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询备份列表 */
    getList() {
      this.loading = true
      listBackups(this.$store.getters.userId).then(response => {
        this.backupList = response.data || []
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 查看备份文件 */
    handleViewBackup(row) {
      this.currentBackup = row
      this.fileLoading = true
      this.fileDialogVisible = true
      
      listBackupFiles(this.$store.getters.userId, row.backupId).then(response => {
        if (response.code === 200 && response.data) {
          try {
            // 如果返回的是JSON字符串，需要解析
            if (typeof response.data === 'string') {
              const data = JSON.parse(response.data)
              this.backupFiles = data.files || []
            } else {
              this.backupFiles = response.data.files || []
            }
          } catch (e) {
            this.backupFiles = []
            this.$message.error('解析备份文件数据失败')
          }
        } else {
          this.backupFiles = []
        }
        this.fileLoading = false
      }).catch(() => {
        this.fileLoading = false
        this.backupFiles = []
      })
    },
    /** 创建备份 */
    handleCreateBackup() {
      this.$confirm('确认创建新的备份？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        createBackup(this.$store.getters.userId).then(response => {
          this.$modal.msgSuccess('创建备份成功')
          this.getList()
        }).finally(() => {
          this.loading = false
        })
      })
    },
    /** 恢复备份 */
    handleRestore(row) {
      this.currentBackup = row
      this.handleViewBackup(row) // 先查看文件
    },
    /** 恢复单个文件 */
    handleRestoreFile(file) {
      this.selectedFiles = [file]
      this.restoreDialogVisible = true
    },
    /** 确认恢复 */
    confirmRestore() {
      if (!this.currentBackup || this.selectedFiles.length === 0) {
        this.$message.warning('请选择要恢复的文件')
        return
      }
      
      this.restoreLoading = true
      const fileIds = this.selectedFiles.map(file => file.id)
      
      restoreFiles({
        userId: this.$store.getters.userId,
        backupId: this.currentBackup.backupId,
        fileIds: fileIds
      }).then(response => {
        this.$modal.msgSuccess('文件恢复成功')
        this.restoreDialogVisible = false
      }).finally(() => {
        this.restoreLoading = false
      })
    },
    /** 格式化文件大小 */
    formatFileSize(size) {
      if (!size) return '0 B'
      
      const units = ['B', 'KB', 'MB', 'GB', 'TB']
      let index = 0
      let fileSize = size
      
      while (fileSize >= 1024 && index < units.length - 1) {
        fileSize /= 1024
        index++
      }
      
      return fileSize.toFixed(2) + ' ' + units[index]
    }
  }
}
</script>

<style scoped>
.backup-toolbar {
  margin-bottom: 20px;
}
</style> 